package com.ungao.tools.generator.converter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class HumpConverter implements IConverter {
    private static final ThreadLocal<Pattern> LINE_PATTERN = ThreadLocal.withInitial(() -> Pattern.compile("_(\\w)"));
    private static final ThreadLocal<Pattern> HUMP_PATTERN = ThreadLocal.withInitial(() -> Pattern.compile("[A-Z]"));

    /**
     * 驼峰转下划线
     *
     * @param content
     * @return
     */
    @Override
    public String toColumn(String content) {
        Matcher matcher = HUMP_PATTERN.get().matcher(content);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(buffer, "_" + matcher.group(0).toUpperCase());
        }
        matcher.appendTail(buffer);
        return buffer.toString().toUpperCase();
    }

    /**
     * 下划线转驼峰
     *
     * @param content
     * @return
     */
    @Override
    public String toField(String content) {
        Matcher matcher = LINE_PATTERN.get().matcher(content);
        StringBuffer buffer = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(buffer, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }

    /**
     * 表名称转别名
     *
     * @param content
     * @return
     */
    @Override
    public String toAlias(String content) {
        Matcher matcher = LINE_PATTERN.get().matcher(content);
        StringBuilder builder = new StringBuilder();
        while (matcher.find()) {
            builder.append(matcher.group(1));
        }
        if (builder.length() == 0) {
            builder.append(content);
        }
        return builder.toString();
    }
}
